/*
Copyright (C) 2010 
Author		  Oliver Schenk
Contact		  Oliver.Schenk76@gmail.com

This program is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; 
if not, see <http://www.gnu.org/licenses/>.
*/

package SelfBookingSystem;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import SelfBookingSystem.MyFramework.ContactAPI;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class StoreAdminValues extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(StoreAdminValues.class.getName());



	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {

		//Variablen Deklaration
		Boolean GoodCredetentials=true;
		String hash = new String();
		String AppID = new String();
		int result=0;
		String tmp = "";
		if (req.getParameter("AppID").compareTo(tmp) > 0){
			AppID = req.getParameter("AppID");
		}else{
				AppID = "xxx"; // Dummy value
		}
		try{

			URL feedUrl = new URL(req.getParameter("GoogleCalendarURL"));
			CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
			myService.setUserCredentials(req.getParameter("EmailAddress"), req.getParameter("Password"));
			// Send the request and receive the response:
			CalendarEventFeed myFeed = myService.getFeed(feedUrl, CalendarEventFeed.class);
		}catch(AuthenticationException e){
			GoodCredetentials=false;
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
		}


	if(GoodCredetentials){

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + AdminValues.class.getName() + " where AppID == \"" + AppID  + "\"";
			List<AdminValues> ConfigurationValues = (List<AdminValues>) pm.newQuery(query).execute();


			if (ConfigurationValues.isEmpty()) {
				//Create Random String for AppID if App has no
				//String tmp1 = "";
				if(AppID.contains("xxx")){
					Random random =  new Random();
					long r1 = random.nextLong();
					long r2 = random.nextLong();
					String hash1 = Long.toHexString(r1);
					String hash2 = Long.toHexString(r2);
					hash = hash1 + hash2;
				}
				AdminValues values = new AdminValues(
req.getParameter("GoogleCalendarURL"),req.getParameter("EmailAddress"),req.getParameter("Password"),hash,req.getParameter("BodyBackgroundColor"),req.getParameter("AuthType"));

				pm.makePersistent(values);
				SelfBookingSystem.StoreUserToAppID.StoreUserToAppID(req.getParameter("User").toLowerCase(), hash, "20");
				
				//Create Google Contacts Group
				ContactAPI addGroup = new ContactAPI();
				String GroupID = new String();
				result = addGroup.GetConnection(req.getParameter("EmailAddress"), req.getParameter("Password"));
				//If UserCredentials are not correct return
				if (result!=9999){
					addGroup.CreateGroup("SelfBookingApplication");
					GroupID = addGroup.InsertGroup();
					System.out.println("AddUserInformation - GroupID: " + GroupID);
				}
			}else{
				AdminValues updt = pm.getObjectById(AdminValues.class,req.getParameter("AppID"));
				updt.setGoogleCalendarURL(req.getParameter("GoogleCalendarURL"));
				updt.setEmailAddress(req.getParameter("EmailAddress"));
				updt.setPassword(req.getParameter("Password"));
				updt.setBodyBackgroundColor(req.getParameter("BodyBackgroundColor"));
				updt.setAuthType(req.getParameter("AuthType"));
				}
			} finally {
				pm.close();
			}
				resp.sendRedirect("/Admin/index.jsp?AppID=" + AppID + "&Result=" + result + "&GoodCredentials=true");
		}else{
			resp.sendRedirect("//Admin/index.jsp?GoodCredentials=false");
		}
	}
}
